package com.wuhao.shootclient.pusher.ws.netty.handler;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.takiku.im_lib.defaultImpl.callback.OnMessageArriveListener;
import com.takiku.im_lib.defaultImpl.textWebSocketFrame.DefaultWSMessageReceiveHandler;
import com.takiku.im_lib.entity.AppMessage;
import com.takiku.im_lib.internal.handler.listener.MessageHandler;
import com.wuhao.shootclient.util.LoggerHelper;

import org.json.JSONObject;

import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;

public class WSMessageReceiveHandler implements MessageHandler<TextWebSocketFrame> {
    OnWsMessageArriveListener listener;

    public WSMessageReceiveHandler(OnWsMessageArriveListener onMessageArriveListener) {
        this.listener = onMessageArriveListener;
    }

    @Override
    public boolean isFocusMsg(Object msg) {
        try {
            if (msg instanceof TextWebSocketFrame) {
                TextWebSocketFrame msg1 = (TextWebSocketFrame) msg;
                JSONObject jsonObject = new JSONObject(msg1.text());
                int code = jsonObject.getInt("code");
                if (code == 20 || code == 21 || code == 22 || code == 100001) {
                    return true;
                }
            } else {
                return false;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return false;
    }

    @Override
    public void handleMsg(TextWebSocketFrame textWebSocketFrame) {
        if (listener != null) {
            LoggerHelper.e("handleMsg",textWebSocketFrame.text());
            try {
//                val json =new Json {
//                    isLenient = true
//                    ignoreUnknownKeys = true
//                    coerceInputValues = true
//                }
//                val data = json.decodeFromString < WsDataBean > (textWebSocketFrame.text());
                listener.onMessageArrive(textWebSocketFrame.text());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
